const axios = require('axios');

(async () => {
  console.log('🔄 最终系统验证测试开始...');
  
  let passedTests = 0;
  let totalTests = 0;
  
  const test = async (name, testFn) => {
    totalTests++;
    try {
      await testFn();
      console.log(`✅ ${name}`);
      passedTests++;
    } catch (error) {
      console.log(`❌ ${name}: ${error.message}`);
    }
  };
  
  try {
    // 1. 服务器健康检查
    await test('服务器健康状态', async () => {
      const response = await axios.get('http://localhost:3000/health');
      if (response.data.status !== 'OK') throw new Error('服务器状态异常');
    });
    
    // 2. 活动API状态筛选测试
    await test('活动API - available状态', async () => {
      const response = await axios.get('http://localhost:3000/api/activities?status=available');
      if (!response.data.activities || !Array.isArray(response.data.activities)) {
        throw new Error('返回数据格式错误');
      }
    });
    
    await test('活动API - upcoming状态', async () => {
      const response = await axios.get('http://localhost:3000/api/activities?status=upcoming');
      if (!response.data.activities || !Array.isArray(response.data.activities)) {
        throw new Error('返回数据格式错误');
      }
    });
    
    await test('活动API - ongoing状态', async () => {
      const response = await axios.get('http://localhost:3000/api/activities?status=ongoing');
      if (!response.data.activities || !Array.isArray(response.data.activities)) {
        throw new Error('返回数据格式错误');
      }
    });
    
    await test('活动API - my状态（未登录）', async () => {
      const response = await axios.get('http://localhost:3000/api/activities?status=my');
      if (!response.data.activities || !Array.isArray(response.data.activities)) {
        throw new Error('返回数据格式错误');
      }
      // 未登录应该返回空数组
      if (response.data.activities.length !== 0) {
        throw new Error('未登录用户应该返回空活动列表');
      }
    });
    
    // 3. 徽章API参数验证测试
    await test('徽章API - 正常请求', async () => {
      const response = await axios.get('http://localhost:3000/api/badges');
      if (!response.data.badges || !Array.isArray(response.data.badges)) {
        throw new Error('返回数据格式错误');
      }
    });
    
    await test('徽章API - undefined参数过滤', async () => {
      const response = await axios.get('http://localhost:3000/api/badges?user_id=undefined');
      if (!response.data.badges || !Array.isArray(response.data.badges)) {
        throw new Error('返回数据格式错误');
      }
      // 应该正常处理，不报错
    });
    
    await test('徽章API - 筛选参数', async () => {
      const response = await axios.get('http://localhost:3000/api/badges?filter=available');
      if (!response.data.badges || !Array.isArray(response.data.badges)) {
        throw new Error('返回数据格式错误');
      }
    });
    
    // 4. 用户认证测试
    let authToken = null;
    await test('用户登录', async () => {
      const response = await axios.post('http://localhost:3000/api/auth/login', {
        email: 'alice@student.com',
        password: 'password123'
      });
      if (!response.data.token) throw new Error('登录失败');
      authToken = response.data.token;
    });
    
    // 5. 认证后的API测试
    if (authToken) {
      await test('活动API - my状态（已登录）', async () => {
        const response = await axios.get('http://localhost:3000/api/activities?status=my', {
          headers: { Authorization: `Bearer ${authToken}` }
        });
        if (!response.data.activities || !Array.isArray(response.data.activities)) {
          throw new Error('返回数据格式错误');
        }
      });
      
      await test('徽章API - owned筛选（已登录）', async () => {
        const response = await axios.get('http://localhost:3000/api/badges?filter=owned', {
          headers: { Authorization: `Bearer ${authToken}` }
        });
        if (!response.data.badges || !Array.isArray(response.data.badges)) {
          throw new Error('返回数据格式错误');
        }
      });
    }
    
    // 6. 活动参与测试
    await test('活动参与功能', async () => {
      if (!authToken) throw new Error('需要登录');
      
      try {
        const response = await axios.post('http://localhost:3000/api/activities/3/join', {}, {
          headers: { Authorization: `Bearer ${authToken}` }
        });
        // 可能已经参与过，所以400错误是正常的
        if (response.status !== 200 && response.status !== 400) {
          throw new Error('参与活动API异常');
        }
      } catch (error) {
        if (error.response && error.response.status === 400) {
          // 400错误是正常的（可能已经参与过）
          return;
        }
        throw error;
      }
    });
    
    // 7. 数据库事务测试
    await test('数据库事务功能', async () => {
      // 通过检查活动详情API来验证数据库连接
      const response = await axios.get('http://localhost:3000/api/activities/3');
      if (!response.data.activity) throw new Error('活动详情获取失败');
    });
    
    console.log('\n📊 测试结果总结:');
    console.log(`✅ 通过测试: ${passedTests}/${totalTests}`);
    console.log(`📈 成功率: ${((passedTests / totalTests) * 100).toFixed(1)}%`);
    
    if (passedTests === totalTests) {
      console.log('\n🎉 所有测试通过！系统运行正常！');
    } else {
      console.log('\n⚠️ 部分测试失败，请检查相关功能');
    }
    
  } catch (error) {
    console.error('❌ 测试执行失败:', error.message);
  }
})(); 